﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio.DataAccess;

/// <summary>
/// Summary description for UsersPresenter
/// </summary>
public class UsersPresenter
{
    #region Fields

    IUsersView _view;
    #endregion

    public UsersPresenter(IUsersView view)
    {
        this._view = view;
    }

    public void LoadRoles()
    {
        using (ObligatorioDotNetEntities data = new ObligatorioDotNetEntities())
        {
            this._view.UserRoles = data.Users.Where(u => u.UserId == this._view.UserId).Single().Roles.ToList();
            this._view.Roles = data.Roles.ToList();
        } 
        this._view.Refresh();
    }

    public void AddRoles()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            foreach (var item in this._view.SelectedRoles)
            {
                var hasRoleAlready = data.Users.Where(u => u.UserId == this._view.UserId).Single().Roles.Where(r => r.RoleId == item).Count() != 0;
                if (!hasRoleAlready)
                {
                    var role = data.Roles.Where(r => r.RoleId == item).Single();
                    data.Users.Where(u => u.UserId == this._view.UserId).Single().Roles.Add(role);

                    data.SaveChanges();
                }
            }
        }
        this.LoadRoles();
    }

    public void RemoveRoles()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            foreach (var item in this._view.SelectedUserRoles)
            {
                var role = data.Users.Where(u => u.UserId == this._view.UserId).Single().Roles.Where(r => r.RoleId == item).SingleOrDefault();
                if (role != null)
                {
                    data.Users.Where(u => u.UserId == this._view.UserId).Single().Roles.Remove(role);

                    data.SaveChanges();
                }
            }
        }
        this.LoadRoles();
    }

    public void GetBranches()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            this._view.Branches = data.Branches.ToList();
        }
    }


}